<script>
  import { get } from "svelte/store";
  import { user } from "../store";
  import { navigate } from "svelte-routing";
  import { onMount } from "svelte";

  export let component;
  export let roles;
  export let path;
  export let id;

  let hasAccess = false;

  onMount(() => {
    console.log(`path: ${path}, component: ${component.name}, roles: ${roles}`);
    const currentUser = get(user);

    // 公开路由
    if (!roles) {
      hasAccess = true;
      return;
    }

    // 未登录
    if (!currentUser) {
      navigate(`/login?redirect=${encodeURIComponent(path)}`);
      hasAccess = false;
      return;
    }

    // 检查角色
    if (roles.includes(currentUser.role)) {
      hasAccess = true;
    } else {
      navigate("/403");
      hasAccess = false;
    }
  });

  let props = {};
  if (id) {
    props = { id };
  }
</script>

{#if hasAccess}
  <!-- <svelte:component this={component} {...$$props} /> -->
  <svelte:component this={component} {...props} />
{/if}
